import * as React from 'react';

import TextField from '@material-ui/core/TextField'
import DialogActions from '@material-ui/core/DialogActions'
import DialogContent from '@material-ui/core/DialogContent'
import DialogTitle from '@material-ui/core/DialogTitle'
import Dialog from '@material-ui/core/Dialog'
import Snackbar from '@material-ui/core/Snackbar';
import Alert from '@material-ui/core/Alert';
import Button from '@material-ui/core/Button';
import CssBaseline from '@material-ui/core/CssBaseline';
import Grid from '@material-ui/core/Grid';
import Stack from '@material-ui/core/Stack';
import Box from '@material-ui/core/Box';
import Typography from '@material-ui/core/Typography';
import Container from '@material-ui/core/Container';
import { createTheme, ThemeProvider } from '@material-ui/core/styles';

import { request } from '../../request'
import './index.css'


import Header from './components/Header'
import Item from './components/Item'


const theme = createTheme();

export default class Album extends React.Component {

  state = {
    data: {},
    journalIntroduction: [],
    saying: '',
    random: Math.floor(Math.random() * 98 + 1),
    open: false,
    msg: '',
    dialogOpen: false,
    imgFile: null,
    newIntro: '',
    newContent: ''
  }

  handleUploadFile = (e) => {
    this.setState({
      imgFile: e.target.files[0]
    })
  }

  judge = (arr) => {
    if (arr === []) {
      return (
        <Typography component="h1"
          variant="h2"
          align="center"
          color="text.primary"
          gutterBottom>
          {'你还没有写日记哟'}
        </Typography>
      )
    } else {
      return (
        <Grid container spacing={4}>
          {arr.map((journal) => (
            <Item key={journal.id} {...journal} delete={this.deleteJournal} />
          ))}
        </Grid>
      )
    }
  }

  componentDidMount() {
    //请求用户数据
    request({
      url: '/user/currentUser',
      method: 'GET'
    }).then(res => {
      this.setState(() => {
        return {
          data: res.data
        }
      })

      //请求首页数据
      request({
        url: `/journal/${res.data.id}`,
        method: 'GET'
      }).then(result => {
        this.setState({
          journalIntroduction: result.data
        })
      })

    });

    //获取随机名言
    request({
      url: `/random/${this.state.random}`,
      method: 'GET'
    }).then(res => {
      this.setState({
        saying: res.data
      })
    })
  }

  handleClickOpen = () => {
    this.setState({
      dialogOpen: true
    })
  }

  handleDialogCancle = () => {
    this.setState({
      dialogOpen: false
    })
  }

  handleInputIntro = (e) => {
    this.setState({
      newIntro: e.target.value
    })
  }

  handleInputContent = (e) => {
    this.setState({
      newContent: e.target.value
    })
  }

  handleTo = () => {
    window.open("https://aidn.jp/mikutap/");
  }

  handleDialogCommmit = (e) => {
    let param = new FormData();
    param.append('file', this.state.imgFile, this.state.imgFile.name); // 通过append向form对象添加数据
    param.append('userId', this.state.data.id);
    param.append('introduction', this.state.newIntro);
    param.append('content', this.state.newContent);
    request({
      url: '/oss',
      method: 'POST',
      data: param
    }).then(res => {
      this.setState({
        dialogOpen: false,
        msg: res.msg,
        open: true
      })
      request({
        url: `/journal/${this.state.data.id}`,
        method: 'GET'
      }).then(result => {
        this.setState({
          journalIntroduction: result.data,
          newIntro: '',
          newContent: ''
        })
      })
    })
  }

  //日记删除提醒
  deleteJournal = (m) => {
    this.setState({
      open: true,
      msg: m
    })
    request({
      url: `/journal/${this.state.data.id}`,
      method: 'GET'
    }).then(result => {
      this.setState({
        journalIntroduction: result.data
      })
    })
  }

  handleClose = (event, reason) => {
    if (reason === 'clickaway') {
      return;
    }

    this.setState({
      open: false
    })
  };

  render() {
    return (
      <ThemeProvider theme={theme}>
        <div className="journalMain">
          <CssBaseline />
          <Header nickName={this.state.data.nickName} />
          <main>
            {/* Hero unit */}
            <Box
              sx={{
                bgcolor: 'background.paper',
                pt: 8,
                pb: 6,
              }}
            >
              <Container maxWidth="sm" >
                <Typography
                  component="h1"
                  variant="h2"
                  align="center"
                  color="text.primary"
                  gutterBottom
                  style={{background: 'rgba(200,19,250,0)'}}
                >
                  Daily Life
                </Typography>
                <Typography variant="h5" align="center" color="text.secondary" paragraph>
                  {this.state.saying}
                </Typography>
                <Stack
                  sx={{ pt: 4 }}
                  direction="row"
                  spacing={2}
                  justifyContent="center"
                >
                  <Button variant="contained" onClick={this.handleTo}>每日心境</Button>
                  <Button variant="outlined" onClick={this.handleClickOpen}>妙笔生花</Button>

                  {/* 弹出框 */}
                  <Dialog open={this.state.dialogOpen} >
                    <DialogTitle>创作</DialogTitle>
                    <DialogContent>
                      <TextField
                        autoFocus
                        label="简介"
                        fullWidth
                        variant="standard"
                        onChange={this.handleInputIntro}
                        value={this.state.newIntro}
                      />
                      <TextField
                        autoFocus
                        fullWidth
                        label="随心记"
                        multiline
                        rows={4}
                        variant="standard"
                        onChange={this.handleInputContent}
                        value={this.state.newContent}
                      />
                      <div>
                        <input
                          type="file"
                          title=" "
                          id="uploadFile"
                          accept="image/*"
                          onChange={this.handleUploadFile}
                          style={{ overflow: "hidden" }} />
                      </div>
                    </DialogContent>
                    <DialogActions>
                      <Button onClick={this.handleDialogCancle}>Cancle</Button>
                      <Button type="submit" onClick={this.handleDialogCommmit}>Commit</Button>
                    </DialogActions>
                  </Dialog>

                </Stack>
              </Container>
            </Box>
            <Container sx={{ py: 8 }} maxWidth="md">
              {/* End hero unit */}
              {this.judge(this.state.journalIntroduction)}
            </Container>
          </main>
          {/* Footer */}
          
          {/* End footer */}
          {/* 消息提醒 */}
          <Stack spacing={2} sx={{ width: '100%' }}>
            <Snackbar
              anchorOrigin={{ vertical: 'top', horizontal: 'center' }}
              open={this.state.open}
              autoHideDuration={3000}
              onClose={this.handleClose}
            >
              <Alert onClose={this.handleClose} severity="success" sx={{ width: '100%' }}>
                {this.state.msg}
              </Alert>
            </Snackbar>
          </Stack>
        </div>
      </ThemeProvider>
    );
  }
}
